

//
//  SHUserResetPasswordController.m
//  JiFengDaRen
//
//  Created by SH_iOS on 2017/5/31.
//  Copyright © 2017年 SH_iOS. All rights reserved.
//

#import "SHUserResetPasswordController.h"

@interface SHUserResetPasswordController ()
<UITextFieldDelegate>
@property(nonatomic,strong)UIView      *firstBgView;
@property(nonatomic,strong)UIView      *secondBgView;
@property(nonatomic,strong)UIView      *thirdBgView;
@property(nonatomic,strong)UILabel     *userNameLabel;
@property(nonatomic,strong)UILabel     *verificationCodeLabel;
@property(nonatomic,strong)UILabel     *passwordLabel;
@property(nonatomic,strong)UITextField *userNameTf;
@property(nonatomic,strong)UITextField *passwordTf;
@property(nonatomic,strong)UITextField *verificationCodeTf;
@property(nonatomic,strong)UIButton    *verificationCodeBtn;
@property(nonatomic,strong)UIButton    *modifyBtn;
@end

@implementation SHUserResetPasswordController


-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    [self layoutUI];
    
    
}
#pragma mark -- UI布局
- (void)configUI{
    self.title = @"重置支付密码";
    self.view.backgroundColor = KBASEBGCOLOR;
    self.firstBgView = [[UIView alloc]init];
    self.firstBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.firstBgView];
    
    self.secondBgView = [[UIView alloc]init];
    self.secondBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.secondBgView];
    
    
    self.thirdBgView = [[UIView alloc]init];
    self.thirdBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.thirdBgView];
    
    self.userNameLabel = [[UILabel alloc]init];
    self.userNameLabel.text = @"手机号码";
    self.userNameLabel.textColor = [UIColor colorWithHexString:@"#474958"];
    self.userNameLabel.font = KSystemFont(__I6Width(12));
    [self.firstBgView addSubview:self.userNameLabel];
    
    self.verificationCodeLabel = [[UILabel alloc]init];
    self.verificationCodeLabel.text = @"验证码";
    self.verificationCodeLabel.textColor = [UIColor colorWithHexString:@"#474958"];
    self.verificationCodeLabel.font = KSystemFont(__I6Width(12));
    [self.secondBgView addSubview:self.verificationCodeLabel];
    
    self.passwordLabel = [[UILabel alloc]init];
    self.passwordLabel.text = @"支付密码";
    self.passwordLabel.textColor = [UIColor colorWithHexString:@"#474958"];
    self.passwordLabel.font = KSystemFont(__I6Width(12));
    [self.thirdBgView addSubview:self.passwordLabel];
    
    
    //文本框
    self.userNameTf = [[UITextField alloc]init];
    self.userNameTf.placeholder = @"中国大陆手机号";
    self.userNameTf.delegate = self;
    [self.userNameTf  setValue:[UIColor colorWithHexString:@"#c0c0c7"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.userNameTf  setValue:KSystemFont(__I6Width(14)) forKeyPath:@"_placeholderLabel.font"];
    self.userNameTf.font = KSystemFont(__I6Width(14));
    self.userNameTf.textColor = [UIColor blackColor];
    self.userNameTf.clearButtonMode  = UITextFieldViewModeAlways;
    self.userNameTf.keyboardType = UIKeyboardTypeNumberPad;

    [self.view addSubview: self.userNameTf ];
    
    
    
    self.verificationCodeTf = [[UITextField alloc]init];
    self.verificationCodeTf.placeholder = @"请输入验证码";
    self.verificationCodeTf.delegate = self;
    [self.verificationCodeTf  setValue:[UIColor colorWithHexString:@"#c0c0c7"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.verificationCodeTf  setValue:KSystemFont(__I6Width(14)) forKeyPath:@"_placeholderLabel.font"];
    self.verificationCodeTf.font = KSystemFont(__I6Width(14));
    self.verificationCodeTf.textColor = [UIColor blackColor];
    self.verificationCodeTf.clearButtonMode  = UITextFieldViewModeAlways;
    self.verificationCodeTf.keyboardType = UIKeyboardTypeNumberPad;

    [self.view addSubview: self.verificationCodeTf];
    
    self.passwordTf = [[UITextField alloc]init];
    self.passwordTf.delegate = self;
    self.passwordTf.placeholder =  @"请将支付密码设置为6位数字";
    self.passwordTf.secureTextEntry = YES;
    self.passwordTf.keyboardType = UIKeyboardTypeNumberPad;
    self.passwordTf.font = KSystemFont(__I6Width(14));
    self.passwordTf.textColor = [UIColor blackColor];
    self.passwordTf.keyboardType = UIKeyboardTypeNumberPad;
    [self.passwordTf  setValue:[UIColor colorWithHexString:@"#c0c0c7"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.passwordTf  setValue:KSystemFont(__I6Width(14)) forKeyPath:@"_placeholderLabel.font"];
    self.passwordTf.clearButtonMode = UITextFieldViewModeAlways;
    [self.thirdBgView addSubview:self.passwordTf ];
    
    self.verificationCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.verificationCodeBtn.titleLabel.font = KSystemFont(__I6Width(11));
    [self.verificationCodeBtn setTitleColor:KREDCOLOR forState:UIControlStateNormal];
    [self.verificationCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    [self.verificationCodeBtn addTarget:self action:@selector(getYzm:) forControlEvents:UIControlEventTouchUpInside];
    [self.secondBgView addSubview:self.verificationCodeBtn];
    
    
    
    self.modifyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.modifyBtn.backgroundColor = KREDCOLOR;
    self.modifyBtn.layer.cornerRadius = __I6Width(5);
    self.modifyBtn.layer.masksToBounds = YES;
    self.modifyBtn.titleLabel.font = KSystemFont(__I6Width(16));
    [self.modifyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.modifyBtn setTitle:@"立即重置" forState:UIControlStateNormal];
    [self.modifyBtn setBackgroundImage:[UIImage imageNamed:@"loginHilight"] forState:UIControlStateHighlighted];
    [self.modifyBtn addTarget:self action:@selector(modifyId:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.modifyBtn];
    
    self.firstBgView.layer.borderWidth = 0.5;
    self.firstBgView.layer.borderColor = KLINECOLOR.CGColor;
    self.secondBgView.layer.borderWidth = 0.5;
    self.secondBgView.layer.borderColor = KLINECOLOR.CGColor;
    
    self.thirdBgView.layer.borderWidth = 0.5;
    self.thirdBgView.layer.borderColor = KLINECOLOR.CGColor;
    
}
#pragma mark --- 设置控件位置
-(void)layoutUI{
    //设置约束
    
    
    [self.firstBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(__I6Height(20));
        make.left.equalTo(self.view.mas_left).with.offset(__I6Width(0));
        make.right.equalTo(self.view.mas_right).with.offset(__I6Width(0));
        make.height.mas_equalTo(__I6Height(42));
        
        
    }];
    
    [self.secondBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.firstBgView.mas_bottom).with.offset(__I6Height(20));
        
        make.left.equalTo(self.view.mas_left).with.offset(__I6Width(0));
        make.right.equalTo(self.view.mas_right).with.offset(__I6Width(0));
        make.height.mas_equalTo(__I6Height(42));
        
        
    }];
    
    [self.thirdBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.secondBgView.mas_bottom).with.offset(__I6Height(20));
        
        make.left.equalTo(self.view.mas_left).with.offset(__I6Width(0));
        make.right.equalTo(self.view.mas_right).with.offset(__I6Width(0));
        make.height.mas_equalTo(__I6Height(42));
        
        
    }];
    
    
    [self.userNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.firstBgView.mas_centerY);
        make.left.equalTo(self.firstBgView.mas_left).with.offset(__I6Width(15));
        make.width.mas_equalTo(__I6Width(50));
        make.height.mas_equalTo(__I6Height(42));
        
        
    }];
    
    [self.verificationCodeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.secondBgView.mas_centerY);
        make.left.equalTo(self.secondBgView.mas_left).with.offset(__I6Width(15));
        make.width.mas_equalTo(__I6Width(50));
        make.height.mas_equalTo(__I6Height(42));
        
        
    }];
    
    [self.passwordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.thirdBgView.mas_centerY);
        make.left.equalTo(self.thirdBgView.mas_left).with.offset(__I6Width(15));
        make.width.mas_equalTo(__I6Width(50));
        make.height.mas_equalTo(__I6Height(42));
        
        
    }];
    
    
    
    [self.userNameTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.firstBgView.mas_top).with.offset(__I6Height(0));
        make.left.equalTo(self.userNameLabel.mas_right).with.offset(__I6Width(35));
        make.right.equalTo(self.firstBgView.mas_right).with.offset(__I6Width(-15));
        make.height.mas_equalTo(__I6Height(42));
        
    }];
    
    [self.passwordTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.thirdBgView.mas_top).with.offset(__I6Height(0));
        make.left.equalTo(self.passwordLabel.mas_right).with.offset(__I6Width(35));
        make.right.equalTo(self.thirdBgView.mas_right).with.offset(__I6Width(-15));
        make.height.mas_equalTo(__I6Height(42));
        
    }];
    
    [self.verificationCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.secondBgView.mas_right).with.offset(__I6Height(0));
        make.centerY.mas_equalTo(self.secondBgView.mas_centerY);
        make.width.mas_equalTo(__I6Width(110));
        make.height.mas_equalTo(__I6Height(42));
        
    }];
    
    [self.verificationCodeTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.secondBgView.mas_top).with.offset(__I6Height(0));
        make.left.equalTo(self.verificationCodeLabel.mas_right).with.offset(__I6Width(35));
        make.right.equalTo(self.verificationCodeBtn.mas_left).with.offset(__I6Width(-20));
        make.height.mas_equalTo(__I6Height(42));
        
    }];
    
    
    [self.modifyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.thirdBgView.mas_bottom).with.offset(__I6Height(50));
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(__I6Width(326));
        make.height.mas_equalTo(__I6Height(42));
        
    }];
    
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = KLINECOLOR;
    [self.secondBgView addSubview:line];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(self.secondBgView.mas_centerY);
        make.right.equalTo(self.verificationCodeBtn.mas_left).with.offset(__I6Width(0));
        make.width.mas_equalTo(__I6Width(1));
        make.height.mas_equalTo(__I6Height(30));
        
        
    }];
    
    
}

#pragma mark --- 点击事件
- (void)getYzm:(UIButton *)sender {
    [self.view endEditing:YES];
    if (self.userNameTf.text.length == 0) {
        [self.view makeToast:@"请输入手机号" duration:1 position:@"center"];
        return;
    }
    
    if (![SHHelper justMobile:self.userNameTf.text]) {
        [self.view makeToast:@"手机号格式不正确" duration:1 position:@"center"];
        return;
    }
    
    
    if ( self.userNameTf.text.length != 0){
        [self startTime];
        NSDictionary *dict = @{@"phone":self.userNameTf.text};
        [MyDataService requestAFURL:KYZM httpMethod:@"POST" params:dict data:nil complection:^(id result) {
            NSLog(@"%@",result);
            
            if ([result[@"success"] isEqualToNumber:@(1)]) {
                
                
                
            }
            
            [self.view endEditing:YES];
        }failure:^(id erro) {
            [Tool alertWithMessage:@"请求失败，请检查你的网络情况" title:nil who:self];
        }];
        
        
        
    }else if(self.userNameTf.text.length == 0){
        [self.view makeToast:@"请输入手机号" duration:1 position:@"center"];
        
    }
    
    
    
    
    
}
- (void)startTime{
    __block int timeout=30; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.verificationCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
                self.verificationCodeBtn.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                
                [self.verificationCodeBtn setTitle:[NSString stringWithFormat:@"%@S",strTime] forState:UIControlStateNormal];
                self.verificationCodeBtn.userInteractionEnabled = NO;
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
    
}


- (void)modifyId:(UIButton *)sender {
    [self.view endEditing:YES];
    if (self.userNameTf.text.length == 0) {
        [self.view makeToast:@"请输入手机号" duration:1 position:@"center"];
        return;
    }
    
    if (self.verificationCodeTf.text.length == 0) {
        
        [self.view makeToast:@"请输入验证码" duration:1 position:@"center"];
        return;
    }
    if (self.passwordTf.text.length == 0) {
        
        [self.view makeToast:@"请设置支付密码" duration:1 position:@"center"];
        return;
    }
    if (self.passwordTf.text.length < 6) {
        
        [self.view makeToast:@"支付密码必须大于6位" duration:1 position:@"center"];
        return;
    }
    
    NSDictionary *dict = @{@"phone":self.userNameTf.text,
                           @"pay_password":self.passwordTf.text ,
                           @"verify_code":self.verificationCodeTf.text
                           };
    NSLog(@"密码%@======%@",self.passwordTf.text,dict);
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [MyDataService requestAFURL:KReset_Pay_PassWord httpMethod:@"POST" params:dict  data:nil complection:^(id result) {
        NSLog(@"%@",result);
        if ([result[@"success"] isEqualToNumber:@(1)]) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self.view makeToast:@"重置支付密码成功" duration:1 position:@"center"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
                
                
            });
        }else{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self.view makeToast:result[@"data"] duration:1 position:@"center"];
            
        }
        
    } failure:^(id erro) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.view makeToast:[NSString stringWithFormat:@"%@",erro] duration:1 position:@"center"];
    }];
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark --- 文本框代理

//参数一：range,要被替换的字符串的range，如果是新键入的那么就没有字符串被替换，range.lenth=0,第二个参数：替换的字符串，即键盘即将键入或者即将粘贴到textfield的string
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
    
    if (textField == _passwordTf) {
        
        if (string.length == 0) {
            return YES;
        }
        if (textField.text.length < 6) {
            return YES;
        }else{
            return NO;
        }
        //第一个参数，被替换字符串的range，第二个参数，即将键入或者粘贴的string，返回的是改变过后的新str，即textfield的新的文本内容
        NSString *checkStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
        //正则表达式
        NSString *regex = @"^\\-?([1-9]\\d*|0)(\\.\\d{0,2})?$";
        return [self isValid:checkStr withRegex:regex];
    }else{
        
        return YES;
    }
    
}
//检测改变过的文本是否匹配正则表达式，如果匹配表示可以键入，否则不能键入
- (BOOL) isValid:(NSString*)checkStr withRegex:(NSString*)regex
{
    NSPredicate *predicte = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [predicte evaluateWithObject:checkStr];
}




-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
